package net.xinshi.utils;

import java.util.UUID;

public class TidManager {
    private static final ThreadLocal<String> TIDTREAD_LOCAL = new ThreadLocal<String>();
    private static final ThreadLocal<Long> threadExecuteTimestamp = new ThreadLocal<Long>();
    private static final ThreadLocal<String> FROM_LOCAL = new ThreadLocal<String>();

    /**
     * 设置TID
     * 
     * @param str
     */
    public static void setTid(String str) {
        TIDTREAD_LOCAL.set(str);
    }

    /**
     * 获取TID
     * 
     * @return
     */
    public static String getTransactionUuid() {
        String transactionUuid = TIDTREAD_LOCAL.get();
        // 当tid为空时，则生成一个tid
        if (transactionUuid == null || transactionUuid.trim().length() == 0) {
            transactionUuid = UUID.randomUUID().toString().replace("-", "");
            setTid(transactionUuid);
        }
        return transactionUuid;
    }

    public static void setSysSourceFrom(String sysSourceFrom) {
        FROM_LOCAL.set(sysSourceFrom);

    }

    public static String getSysSourceFrom() {
        return FROM_LOCAL.get();
    }

    public static void setTime(Long timestamp) {
        threadExecuteTimestamp.set(timestamp);
    }

    public static Long getTime() {
        return threadExecuteTimestamp.get();
    }

    public static void clear() {
        TIDTREAD_LOCAL.remove();
        threadExecuteTimestamp.remove();
        FROM_LOCAL.remove();
    }
}
